#!/usr/bin/perl
use warnings;
use strict;
use File::Temp qw( tempfile tempdir );

#******************************************************************************
# File: 
#		perl.pl
# Recipe: 7.11
#		Creating Temporary Files
# Version:
#		0.1
# Author:
#   	Yubei Zhu
# Mail:
#		yubeizhu@gmail.com
# Created at:
#   	2012-08-16  
# Last Update:
#   	2012-08-16
# License: 
#		GPLv3	
#******************************************************************************


################################### Temporary Dir ###################################

# Module File::Temp can support creating temporary files / dirs
# Create temp dir, will not delete it after exit
# Return the dirname
my $sTmpDir = tempdir( );
# /tmp/5ZaWrFtFtP /tmp/lDZRFGeyOP /tmp/VQkM0C2YUP
print "Temporary dir: $sTmpDir\n";

# Create temp dir, will not delete it after exit
my $sTmpCleanDir = tempdir( CLEANUP => 1 );
print "Temporary dir will be removed: $sTmpCleanDir\n";

# Create temp dir at specific dir and this dir must be created ahead
my $sTestDir = "/tmp/test"; 
$sTmpDir = tempdir( DIR => $sTestDir );
print "Temporary dir at test dir $sTestDir: [$sTmpDir]\n";

# The template must end with at least 4 'X' characters
my $sDirTemplate = "TestTmpDirXXXX";  
$sTmpDir = tempdir( $sDirTemplate, DIR => $sTestDir );

# /tmp/test/TestTmpDirvquC
print "Temporary dir with template at test dir $sTestDir: [$sTmpDir]\n";

################################### Temporary File ###################################

# Create a temp file 
my $sFileTemplate = "1111111FileXXXX";

# Get filehandle in scalar context, file will be deleted
my $fhTmpFile = tempfile( $sFileTemplate,  DIR => $sTmpDir );
print "FileHandle only: $fhTmpFile\n"; 

# Get filehandle and filename, file will be keep
$sFileTemplate = "2222222FileXXXX";
my ( $fhTmpFile, $sTmpFileName ) = tempfile( $sFileTemplate, DIR => $sTmpDir );
print "FileName:$sTmpFileName\n";
#print $fhTmpFile "Test\n";# write something
close ( $fhTmpFile ) or die "Can't close file $sTmpFileName:$!";

# Create temp file with more details
$sFileTemplate = "3333333FileXXXX";
# Specify extension and delete it always when program exits
( $fhTmpFile, $sTmpFileName )  =  tempfile( $sFileTemplate,   DIR => $sTmpDir, 
                        				    SUFFIX => ".tmp", UNLINK => 1 ); # Not cleanup






